<template>
  <div class="translation-select">
    <el-select v-model="selectedLanguage" placeholder="Select language" style="width:150px" :popper-class="color === 'night' ? 'nightClass' : ''">
      <el-option v-for="(language, index) in languages" :key="index" :label="language.name" :value="language.code"></el-option>
    </el-select>
    <el-button @click="translate" type="primary" style="margin-left:10px">
      翻译
      <el-icon v-if="loading" class="is-loading"><Loading /></el-icon>
    </el-button>
  </div>
</template>

<script>
import { getgptchat } from '../../api/connrequest'
export default {
  name: 'TranslationSelect',
  props: {
    text: {
      type: String,
      required: true,
    },
    binding: {
      type: String,
      required: true,
    }
  },
  mounted(){
    this.color = localStorage.getItem('isNightMode') || 'night'
  },
  data() {
    return {
      loading: false,
      selectedLanguage: '英语',
      color:'',
      languages: [
        { name: '英语', code: '英语' },
        { name: '中文', code: '中文' },
        { name: '日文', code: '日语' },
        { name: '俄语', code: '俄语' },
        // 添加更多语言
      ],
    };
  },
  methods: {
    async translate() {
      if(!sessionStorage.getItem('Name')){
        this.loading = false
        this.$message.error('发生错误：请先登录帐号')
        return false
      }
      if(this.text === '' || this.text === undefined){
        this.$message.info('翻译失败')
        return false
      }
      const text = this.text.trim();
      this.loading = true
      // const API_ENDPOINT = 'https://api.openai.com/v1/chat/completions';
      // const OPENAI_API_KEY = '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'
      try {
        // let prompt = `translate ${text} ${this.selectedLanguage}`
        let prompt = `Translate this into ${this.selectedLanguage}: ${text}`
        this.apiMessage = [
          {role: 'system', content: 'you are a helpful assistant.'},
        ]
        this.apiMessage.push({role:'user', content: prompt})
        // const response = await axios.post(API_ENDPOINT, {
        //   model: 'gpt-3.5-turbo-0301',
        //   // model: 'gpt-4',
        //   messages: this.apiMessage,
        //   temperature: 0.5, // 采样温度：介于0和2之间。较高的值（如0.8）会使输出更随机，而较低的值（如0.2）则会使其更加集中和确定性
        // }, {
        //   headers: {
        //     'Content-Type': 'application/json',
        //     'Authorization': `Bearer ${OPENAI_API_KEY}` // 在环境变量中设置 OpenAI API 密钥
        //   }
        // });
        let model = JSON.parse(sessionStorage.getItem('AiMode')).Translate
        const gptdata = {
          Data: {
            model: model || 'gpt-3.5-turbo',
            messages: this.apiMessage,
          }
        }
        const response = await getgptchat(gptdata)
        this.loading = false
        const translation = response.Data.choices[0].message.content;
        this.$emit('translation', {translation, binding: this.binding});
      } catch (error) {
        this.loading = false
        this.$message.error('发生错误，请重试！')
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.translation-select {
  position: absolute;
  right: 20px;
  bottom: 10px;
  display: flex;
  align-items: center;
}

</style>
